package master

import (
	"context"
	"bussanq/gocron/common"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)
// mongodb日志管理
type LogMgr struct {
	client *mongo.Client
	logCollection *mongo.Collection
}

var (
	G_logMgr *LogMgr
)

func InitLogMgr() (err error) {
	var (
		client *mongo.Client
	)

	// 建立mongodb连接
	con := context.TODO()
	//1、建立连接
	opt := options.Client()
	opt.SetConnectTimeout(time.Duration(G_config.MongodbConnectTimeout)*time.Millisecond).ApplyURI(G_config.MongodbUri)
	if client,err = mongo.Connect(con,opt); err != nil {
		return
	}

	G_logMgr = &LogMgr{
		client: client,
		logCollection: client.Database("cron").Collection("log"),
	}
	return
}

// 查看任务日志
func (logMgr *LogMgr) ListLog(name string, skip int, limit int) (logArr []*common.JobLog, err error){
	var(
		cursor *mongo.Cursor
		con context.Context
		jobLog *common.JobLog
	)

	//初始化返回
	logArr = make([]*common.JobLog,0)

	filter := &common.JobLogFilter{JobName:name}
	logsort := &common.SortLogByStartTime{SortOrder:-1}
	skip64 := int64(skip)
	limit64 := int64(limit)
	findOpt := &options.FindOptions{
		Limit:&limit64,
		Skip:&skip64,
		Sort:logsort,
	}
	if cursor, err = logMgr.logCollection.Find(con,filter,findOpt);err != nil {
		return
	}
	defer cursor.Close(con)

	for cursor.Next(context.TODO()) {
		jobLog = &common.JobLog{}

		// 反序列化BSON
		if err = cursor.Decode(jobLog); err != nil {
			continue // 有日志不合法
		}

		logArr = append(logArr, jobLog)
	}
	return
}